package com.bluesky.android.utils;

import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteException; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.database.sqlite.SQLiteDatabase.CursorFactory; 
import android.util.Log;

public class MangaDBHelper extends SQLiteOpenHelper {
	private static final String CREATE_MANGA_TABLE="create table " + 
		MangaContants.MANGA_TABLE_NAME + " ( " + 
		MangaContants.MANGA_ID + " integer primary key autoincrement, " +
		MangaContants.MANGA_TITLE + " varchar(255) not null, " +
		MangaContants.MANGA_AUTHOR + " varchar							(255) not null, " + 
		MangaContants.MANGA_IMAGE_LINK + " text not null, " +
		MangaContants.MANGA_LINK + " text not null, " +
		MangaContants.MANGA_SUMMARY + " text not null);";
	
	private static final String CREATE_CHAPTER_TABLE =	" create table " + 
		MangaContants.CHAPTER_TABLE_NAME + " ( " +
		MangaContants.CHAPTER_ID + " integer primary key autoincrement, " + 
		MangaContants.CHAPTER_TITLE + " varchar(255) not null, " +
		MangaContants.CHAPTER_MANGA_ID_FK + " int, " +
		MangaContants.CHAPTER_LINK + " text not null, " + 
		MangaContants.CHAPTER_DATE + " text not null, " + 
		MangaContants.CHAPTER_CURRENT_IMAGE_POSITION + " int, " +
		MangaContants.CHAPTER_IS_DOWNLOADING + " tinyint, " +
		MangaContants.CHAPTER_SAVE_ON_DISK + " tinyint);";
	
	private static final String CREATE_IMAGE_TABLE =
		" create table " + 
		MangaContants.IMAGE_TABLE + " ( " +
		MangaContants.IMAGE_INDEX + " integer, " +
		MangaContants.IMAGE_CHAPTER_ID_FK + " int , " +
		MangaContants.IMAGE_LINK + " text not null); ";
	public MangaDBHelper(Context context, String name, CursorFactory factory, 
			int version) {
		super(context, name, factory, version);		
	}
	
	@Override 
	public void onCreate(SQLiteDatabase db) {
		Log.v("MangaDBHelper onCreate","Creating all the tables"); 
		try {
			db.execSQL(CREATE_MANGA_TABLE); 
			db.execSQL(CREATE_CHAPTER_TABLE);
			db.execSQL(CREATE_IMAGE_TABLE);
		} catch(SQLiteException ex) {
			Log.v("Create table exception", ex.getMessage()); 
		}
	}
	@Override 
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion 
				+ " to " + newVersion 
				+ ", which will destroy all old data");
		try
		{
			db.execSQL("drop table if exists " + MangaContants.MANGA_TABLE_NAME + ";");
			db.execSQL("drop table if exists " + MangaContants.CHAPTER_TABLE_NAME + ";");
			db.execSQL("drop table if exists " + MangaContants.IMAGE_TABLE + ";");
		}catch(SQLiteException ex) {
			Log.v("Delete table exception", ex.getMessage()); 
		}		
		onCreate(db);
	} 
}
